<template>
  <div class="session" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time
              @changeType="changeType"
              type="other"
              @isFold="isShowFold"
              :query="query"
              :isTimePeriod="true"
            ></date-time>
            <el-button
              type="primary"
              class="primary_btn fr find"
              v-on:click.stop="search"
              >{{ $t('public.search2') }}</el-button
            >
            <div class="clear"></div>
          </div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="accs">
                  <span class="access">{{ $t('report.imAccessId') }}：</span>
                  <el-select
                    size="mini"
                    v-model.trim="selectedAccessIdList"
                    multiple
                    filterable
                    :placeholder="$t('report.searchByName')"
                  >
                    <el-option
                      v-for="item in accessIdOptions"
                      :label="item.label"
                      :value="item.value"
                      :key="item.value"
                    >
                    </el-option>
                  </el-select>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="$t('report.sessionNumSurvey')"></affix>
      <div class="situation">
        <el-row>
          <el-col v-for="(item, index) in situation" :span="6" :key="index">
            <span class="sum_name">{{ item.name }}</span>
            <span class="sit_num">{{ item.value }}</span>
          </el-col>
        </el-row>
      </div>
      <affix :label="title"></affix>
    </div>
    <div :id="id">
      <el-row class="ichars">
        <highcharts :options="highchartsDefaultOptions"></highcharts>
        <div class="notes">
          <span class="light"
            >{{ $t('report.hicharsNotes') }}: <span></span
            >{{ $t('report.hicharsLight') }}</span
          >
          <span class="dark"><span></span>{{ $t('report.hicharsDark') }}</span>
        </div>
      </el-row>
      <div class="tab">
        <div class="export">
          <el-button
            :class="isEcommerce ? 'isEcommerce' : ''"
            class="primary_btn fr formal"
            v-if="configFormula"
            @click="$refs.formulaEditorDialog.open()"
            >{{ $t('report.formalTitle') }}</el-button
          >
          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd && !isEcommerce"
            @click.stop="exportXls"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button
            class="primary_btn fr report_excel_btn"
            v-if="!isEcommerce"
            @click.stop="exportXlsx"
            >{{ $t('report.exportXls') }}</el-button
          >

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{
            $t('report.exportPDF')
          }}</el-button>
          <el-select
            @change="changeTimeType"
            class="fr"
            v-model="halfTrend"
            size="mini"
            v-show="isShowTimeTurn && !isEcommerce"
          >
            <el-option
              :label="$t('report.oneHourTrend')"
              :value="false"
            ></el-option>
            <el-option
              :label="$t('report.halfHourTrend')"
              :value="true"
            ></el-option>
          </el-select>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{
                  $t('report.toggleInstructe')
                }}</span>
              </template>
              <div>
                1. {{ $t('report.allConSationNumber') }}<br />
                2. {{ $t('report.imPersonSessionNum') }}<br />
                3. {{ $t('report.imRobotSessionNum') }}<br />
                4. {{ $t('report.imTurnToPerson') }}<br />
                5. {{ $t('report.imLostSessionCount') }}<br />
                6. {{ $t('report.activeClaimRobotSessionCount') }}<br />
                7. {{ $t('report.initiatingNumber') }}<br />
                8. {{ $t('report.imSeatInviteNum') }}<br />
                9. {{ $t('report.imFineSessionNum1') }}<br />
                10. {{ $t('report.imBadSessionNum1') }}<br />
                11. {{ $t('report.imKindSessionNum1') }}<br />
                12. {{ $t('report.queueGiveUpCount') }}<br />
                13. {{ $t('report.sessionsQueueCount')}}<br/>
                14. {{ $t('report.SessionTimeTrendTableOne')}}<br/>
                15. {{ $t('report.agentInvitedSessionsNumber')}}<br/>
                16. {{ $t('report.transferSessionsNumber')}}<br/>
                <p class="custom_alg">{{ $t('report.ziDingYi') }}：</p>
                <p v-for="(item, index) in formulas" :key="item.name">
                  {{ index + 17 }}.{{ item.formulaInstr }}
                </p>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table
          :data="tableData"
          :sum="totalData"
          :config="[...headOptions.Config, ...formulasConfig]"
        ></report-table>
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      modal-append-to-body
      lock-scroll
      top="10%"
      :title="$t('report.reportExportHelp')"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <span>{{ $t('report.reportExportTipTitle') }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{
          $t('public.cancel')
        }}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{
          $t('public.confirm')
        }}</el-button>
      </span>
    </el-dialog>
    <!-- 自定义公式组件 -->
    <FormulaEditorDialog
      ref="formulaEditorDialog"
      :headOptionsConfig="headOptions.Config"
      @closeFormulaDialog="closeFormulaDialog"
      reportName="会话数时间趋势报表"
      :reportType="id"
    />
  </div>
</template>
<script>
import affix from '../../../ui-modules/affix/Affix.vue'
import unfold from '../../../ui-modules/unfold/index.vue'
import dateTime from '../base/datetime.vue'
import reportTable from '../base/reportTable.vue'
import { deepClone, isHasFunc } from '@/utils/m7Utils.js'
import { exportReportPdf, headOptionsToXlsxHeaders, checkTime, searchTime, colorConfigArr, mixData } from '@/utils/reportUtils.js'
import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
import FormulaEditorDialog from '../base/FormulaEditorDialog.vue'
export default {
  name: 'im_report_session_time',
  data () {
    return {
      configFormula: true, // 自定义公式的权限
      tableData: [], // table展示数据
      dateType: 'day', // 时间类型
      halfTrend: false, // 时间切换展示
      isEcommerce: this.$store.getters.isEcommerce ? true : false,
      isFold: false,
      selectedAccessIdList: [],
      accessIdOptions: [],
      situation: [],
      id: 'im_report_session_time',
      title: this.$t('report.imReportSessionTime'),
      loading: false,
      groupName: 'hourId',
      timeType: 'day',
      query: {},
      dialogVisible: false,
      serverData: [],
      headOptions: { Config: [], data: [] },
      highchartsDefaultOptions: {
        chart: { type: '', animation: false },
        colors: colorConfigArr,
        xAxis: {
          categories: [],
          title: {
            enabled: true,
            text: '',
            style: { fontWeight: 'normal' }
          }
        },
        yAxis: {
          gridLineColor: '#e6e6e6',
          allowDecimals: false,
          title: { text: '' },
          showEmpty: false
        },
        title: { text: this.$t('report.imReportSessionTime') },
        legend: { align: 'center', verticalAlign: 'top', y: 30 },
        tooltip: {
          pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}{point.valueSuffix}</b><br/>',
          shared: true
        },
        credits: { enabled: false },
        series: []
      },
      isSearch: false,
      formulas: [] // 公式数据
    }
  },
  components: {
    affix,
    unfold,
    dateTime,
    reportTable,
    FormulaEditorDialog
  },
  watch: {
    // 监测自定义公式变化 更新数据
    formulas (cur, old) {
      if (this.isSearch) {
        return
      }
      if (!this.serverData || this.serverData.length === 0) {
        return
      }
      this.serverData = mixData(deepClone(this.serverData), this.formulas)
    }
  },
  computed: {
    isShowTimeTurn () {
      let type = ['day']
      return type.includes(this.dateType)
    },
    // 自定义表头
    formulasConfig () {
      return this.formulas.map((d, i) => {
        return {
          displayname: d.displayname,
          name: d.name,
          order: d.order,
          show: d.show,
          timeType: 'none',
          digits: d.digits,
          type: d.type
        }
      })
    },
    // tableData () {
    //   return this.getTableData(this.serverData, this.groupName)
    // },
    totalData () {
      this.situation = []
      if (!this.serverData || this.serverData.length === 0) {
        let headerConfig = this.headOptions.Config || []
        for (let i = 0; i < headerConfig.length; i++) {
          if (headerConfig[i].name === 'reportTime') {
            continue
          }
          this.situation.push({
            name: headerConfig[i].displayname,
            value: 0
          })
        }
        return [{ reportTime: this.$t('report.total') }]
      }
      let headerConfig = this.headOptions.Config || []
      let datas = this.serverData
      let total = {
        reportTime: this.$t('report.total')
      }
      for (let i = 0; i < headerConfig.length; i++) {
        if (headerConfig[i].name === 'reportTime') {
          continue
        }
        for (let j = 0; j < datas.length; j++) {
          if (!isNaN(datas[j][headerConfig[i].name])) {
            if ((headerConfig[i].name in total) === false) {
              total[headerConfig[i].name] = 0
            }
            total[headerConfig[i].name] += datas[j][headerConfig[i].name]
          }
        }
        this.situation.push({ name: headerConfig[i].displayname, value: total[headerConfig[i].name] })
      }
      total = mixData([total], this.formulas)[0]
      return [total]
    }
  },
  methods: {
    // 图表展示方法
    getHighchartsOptions () {
      let options = deepClone(this.highchartsDefaultOptions)
      if (!this.serverData || this.serverData.length === 0) {
        options.series = []
        options.xAxis.categories = []
        return options
      }

      let headerConfig = this.headOptions.Config || []
      let datas = deepClone(this.serverData)
      let categoriesArray = []
      let seriesArray = []

      headerConfig.forEach(item => {
        if (!item.show) {
          return
        }
        if (item.name === 'reportTime') {
          return
        }
        let serie = { name: item.displayname, data: [], valueName: item.name }
        seriesArray.push(serie)
      })

      for (let i = 0; i < datas.length; i++) {
        if (this.isShowTimeTurn && this.halfTrend) {
          categoriesArray.push((datas[i]['reportTime']))
        } else {
          categoriesArray.push(this.formatChartTime(datas[i][this.groupName]))
        }
        for (let j = 0; j < seriesArray.length; j++) {
          seriesArray[j].data.push(datas[i][seriesArray[j].valueName])
        }
      }

      options.xAxis.categories = categoriesArray
      options.series = seriesArray

      return options
    },
    // 自定义公式弹窗关闭外抛事件
    closeFormulaDialog () {
      this.isSearch = false
      this.$store.dispatch('queryFetchFormula', { type: this.id }).then((resp) => {
        if (resp.success) {
          this.formulas = resp.data.Formulas
          this.serverData = deepClone(mixData(this.serverData, this.formulas))
          this.tableData = this.getTableData(this.serverData, this.groupName)
        }

      })
    },
    // 切换时间查看触发
    changeTimeType (val) {
      this.$cookies.set('default_search_time', val, -1)
      this.search()
    },
    // 子组件切换时间类型传上来得方法 触发计算属性
    changeType (type) {
      this.dateType = type
    },
    getTotalData (serverData, headOptions) {
      if (!serverData || serverData.length === 0) {
        return [{ reportTime: this.$t('report.total') }]
      }
      let headerConfig = headOptions.Config || []
      let datas = serverData
      let total = {
        reportTime: this.$t('report.total')
      }
      for (let i = 0; i < headerConfig.length; i++) {
        if (headerConfig[i].name === 'reportTime') {
          continue
        }
        for (let j = 0; j < datas.length; j++) {
          if (!isNaN(datas[j][headerConfig[i].name])) {
            if ((headerConfig[i].name in total) === false) {
              total[headerConfig[i].name] = 0
            }
            total[headerConfig[i].name] += datas[j][headerConfig[i].name]
          }
        }
      }
      total = mixData([total], this.formulas)[0]
      return [total]
    },
    getTableData (serverData, groupName) {
      if (!serverData || serverData.length === 0) {
        return []
      }
      let data = deepClone(serverData)
      if (!(this.isShowTimeTurn && this.halfTrend)) {
        data.forEach(item => {
          item.reportTime = this.formatReportTime(item[groupName])
        })
      }
      return data
    },
    isShowFold (bool) {
      this.isFold = bool
    },
    formatReportTime (reportTime) {
      if (!reportTime) {
        return ''
      } else if (this.groupName === 'monthId') {
        return `${reportTime.substring(0, 4)}-${reportTime.substring(4, 6)}`
      } else if (this.groupName === 'dayId') {
        return `${reportTime.substring(0, 4)}-${reportTime.substring(4, 6)}-${reportTime.substring(6, 8)}`
      } else {
        return `${reportTime.substring(0, 4)}-${reportTime.substring(4, 6)}-${reportTime.substring(6, 8)} ${reportTime.substring(8, 10)}:00:00`
      }
    },
    formatChartTime (reportTime) {
      if (!reportTime) {
        return ''
      } else if (this.groupName === 'monthId') {
        return reportTime.substring(4, 6)
      } else if (this.groupName === 'dayId' && this.timeType === 'month') {
        return reportTime.substring(6, 8)
      } else if (this.groupName === 'dayId' && this.timeType === 'other') {
        return `${reportTime.substring(0, 4)}-${reportTime.substring(4, 6)}-${reportTime.substring(6, 8)}`
      } else {
        return reportTime.substring(8, 10)
      }
    },
    getSearchQueryData () {
      let data = {
        reportType: this.id,
        account: this.$store.state.session.user.account,
        query: { reportType: this.id },
        user: {
          type: this.$store.state.session.user.type,
          moduleUsers: this.$store.state.session.user.moduleUsers
        }
      }
      if (this.dateType === 'day') {
        data.query.halfTrend = this.halfTrend
      }
      let query = deepClone(this.query)
      if (query.timeType === 'other') {
        // 校验类型与时间
        let message = checkTime(query.StartTime, query.EndTime, false, true)
        if (message !== true) {
          this.$message.error(this.$t(message))
          return
        }
      }
      if (query.timeType === 'other' && (query.StartTime === '' || query.EndTime === '')) {
        let date = new Date()
        let year = '' + date.getFullYear()
        query.timeType = 'year'
        query.yearReport = year
      }
      if (this.selectedAccessIdList.length > 0) {
        query.selectedAccessIdList = this.selectedAccessIdList.join(',')
      }
      data.query = Object.assign({}, data.query, query)
      return data
    },
    search () {
      var queryData = this.getSearchQueryData()

      if (!queryData) {
        return
      }
      var query = queryData.query
      this.loading = true
      this.$store.dispatch('queryImSessionTimeReport', queryData).then((res) => {
        if (this.$store.state.report.customExportData) {
          res = JSON.parse(this.$store.state.report.customExportData)
        }
        if (query.timeType === 'year') {
          this.groupName = 'monthId'
        } else if (query.timeType === 'month') {
          this.groupName = 'dayId'
        } else if ((query.timeType === 'other') && query.timePeriod) {
          //    查询方式为  自定义 或  日报  并且 定时间段统计  则更换 时间 渲染的字段
          this.groupName = 'dayId'
        } else if (query.timeType === 'day') {
          this.groupName = 'hourId'
        } else if (query.timeType === 'other') {
          this.groupName = 'dayId'
        }
        this.timeType = query.timeType
        //  图表标题 加入 定时段的 时间
        let highchartsTitle = ''
        if (query.timePeriod) {
          let timePeriodStartStr = query.timePeriodStart || '00:00'
          let timePeriodEndStr = query.timePeriodEnd || '23:59'
          highchartsTitle = '(' + timePeriodStartStr + '~' + timePeriodEndStr + ')'
        }
        this.highchartsDefaultOptions.title.text = this.$t('report.imReportSessionTime') + highchartsTitle
        // 表头
        // this.headOptions = deepClone(res.tableHeader) || this.headOptions

        // this.serverData = deepClone(res.data) || this.serverData
        this.isSearch = true
        this.$store.dispatch('queryFetchFormula', { type: this.id }).then((resp) => {
          if (resp.success) {
            this.formulas = resp.data.Formulas
            // 表头
            this.headOptions = deepClone(res.tableHeader) || this.headOptions
            this.serverData = deepClone(mixData(res.data, this.formulas)) || deepClone(mixData(this.serverData, this.formulas))
            this.tableData = this.getTableData(this.serverData, this.groupName)
            this.highchartsDefaultOptions = this.getHighchartsOptions()
            this.loading = false
          }
        })
      })
    },
    exportXlsx () {
      var queryData = this.getSearchQueryData()

      if (!queryData) {
        return
      }
      var query = queryData.query
      this.loading = true
      this.$store.dispatch('queryImSessionTimeReport', queryData).then((res) => {
        if (this.$store.state.report.customExportData) {
          res = JSON.parse(this.$store.state.report.customExportData)
        }
        this.loading = false
        var headOptions = deepClone(res.tableHeader) || []
        var serverData = mixData(deepClone(res.data), this.formulas) || []
        var sum = []
        if (serverData.length !== 0) {
          sum = this.getTotalData(serverData, headOptions)
        }
        var groupName = 'monthId'
        if (query.timeType === 'year') {
          groupName = 'monthId'
        } else if (query.timeType === 'month') {
          groupName = 'dayId'
        } else if ((query.timeType === 'other') && query.timePeriod) {
          //    查询方式为  自定义 或  日报  并且 定时间段统计  则更换 时间 渲染的字段
          groupName = 'dayId'
        } else if (query.timeType === 'day') {
          groupName = 'hourId'
        } else if (query.timeType === 'other') {
          groupName = 'dayId'
        }

        var tableData = this.getTableData(serverData, groupName).concat(sum)
        var headers = headOptionsToXlsxHeaders([...headOptions.Config, ...this.formulasConfig])

        var dh = XlsxUtil.getDownloadHelper(headers, tableData)
        var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
        dh.download(this.$t('report.imReportSessionTime') + timeStamp)
      })
    },
    exportXls () {
      let data = {
        Method: 'exportImSessionTime',
        Query: { reportType: this.id, user: this.$store.state.session.user._id }
      }
      let query = deepClone(this.query)
      if (query.timeType === 'other_half_hour') {
        let message = checkTime(query.StartTime, query.EndTime, true, false) // 校验类型与时间
        if (message !== true) {
          this.$message.error(this.$t(message))
          return
        }
      }
      if (this.selectedAccessIdList.length > 0) {
        query.selectedAccessIdList = this.selectedAccessIdList.join(',')
      }
      data.Query = Object.assign({}, data.Query, query)
      this.$store.dispatch('exportImSessionTimeReport', data)
    },
    exportPdf () {
      this.dialogVisible = true
    },
    confirm () {
      this.dialogVisible = false
      exportReportPdf({ title: this.$t('report.webchat') + this.$t('report.imReportSessionTime') + searchTime(this.query), id: this.id })
    }
  },
  beforeMount () {
    if (isHasFunc('func_forbid_config_formula', this.$store.state.session.user)) {
      this.configFormula = false // 没有自定义公式的配置权限
    }
    let type = this.isEcommerce ? 'ecommerceAccessId' : 'accessIds'
    this.$store.dispatch('getCache', { type: type }).then(accessIds => {
      this.accessIdOptions = accessIds.map(accessId => ({ label: `${accessId.name}[${accessId.platform}]`, name: accessId.name, platform: accessId.platform, value: accessId._id }))
    })
    this.$nextTick(() => {
      this.search()
    })
    let default_search_time = this.$cookies.get('default_search_time')
    // this.halfTrend
    console.log(typeof default_search_time, default_search_time)
    this.halfTrend = default_search_time === 'true' ? true : false
  }
}
</script>
<style lang="stylus" scoped>
@import '../../../../assets/common.styl'
.session
  .accs
    margin 14px 0 0px 0px
    .access
      margin-right 10px
    .el-select
      width 600px
  .tab
    .export
      .el-select
        width 110px
    .deploy
      .tip
        margin-left 0px
  .isEcommerce
    margin-left 10px
</style>
